141. 环形链表
为保证权益,题目请参考 141. 环形链表(From LeetCode).
解决方案1
Python
python
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# 哈希表
# class Solution:
# def hasCycle(self, head: ListNode) -> bool:
# a = set()
# while True:
# if head is None:
# return False
# if head in a:
# return True
# a.add(head)
# head = head.next
# return False
# 快慢指针
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if head is None:
return False
low = head
fast = head
while True:
fast = fast.next
if fast is None:
return False
fast = fast.next
if fast is None:
return False
low = low.next
if fast is low:
return True
return False
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39